package edu.drexel.cs575.taskManager.gui.controller.tasks;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import edu.drexel.cs575.taskManager.common.ServiceFactory;
import edu.drexel.cs575.taskManager.common.serviceDropSpot.broker.BrokerCaller;
import edu.drexel.cs575.taskManager.common.serviceDropSpot.broker.GeneralSecurityException_Exception;
import edu.drexel.cs575.taskManager.common.serviceDropSpot.broker.IOException_Exception;
import edu.drexel.cs575.taskManager.common.serviceDropSpot.notification.NotificationCaller;
import edu.drexel.cs575.taskManager.gui.Helper;
import edu.drexel.cs575.taskManager.gui.model.tasks.Task;
import edu.drexel.cs575.taskManager.gui.model.tasks.TaskList;
import edu.drexel.cs575.taskManager.gui.model.users.LoginCredentials;

@Controller

public class TaskController {
	
	private static String listId = "MTUzMjM1Njc5Mjg4MDU1NTUzMTE6MjY5OTU3NTg1OjA";
	
	public ModelAndView taskDetail(){
		return null;
	}
	
	@RequestMapping("tasks")
	public ModelAndView taskIndex(HttpServletRequest request){
		if(Helper.isLoggedIn(request)){
			try{
				BrokerCaller taskService = ServiceFactory.getTaskService();
				TaskList taskList = getTaskList(request, taskService, Helper.getUserName(request));
				return new ModelAndView("displayAllTasks", "command", taskList);
			}
			catch(Throwable t){
				TaskList taskList = getTaskList(Helper.getUserName(request));
				return new ModelAndView("displayAllTasks", "command", taskList);
			}

		}
		else{
			return new ModelAndView("index", "command", new LoginCredentials());
		}
	}
	
	public static TaskList getTaskList(String userName) {
		TaskList taskList = new TaskList();
		taskList.getTasks().add(new Task("Task 1"));
		taskList.getTasks().add(new Task("Second task"));
		return taskList;
	}

	public static TaskList getTaskList(HttpServletRequest request, BrokerCaller taskService, String userName) {
		// TODO - finish grabbing tasks from task service.
		TaskList taskList = new TaskList();
		try {
			
			List<Cookie> cookies =  Arrays.asList(request.getCookies());
			
			Iterator<Cookie> iter = cookies.iterator();
			while(iter.hasNext()){
				Cookie next = iter.next();
				if(next.getName().contains("task")){
					String value = next.getValue();
					String taskName = taskService.tgetTaskName(listId, value);
					taskList.getTasks().add(new Task(taskName));
				}
			}
		} catch (GeneralSecurityException_Exception | IOException_Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return taskList;
	}

	@RequestMapping("createTask")
	public ModelAndView createTask(){
		return new ModelAndView("createTask", "command", new Task());
	}
	
	public void updateTask(Object obj){
		
	}
	
	@RequestMapping(value = "/createTask", method = RequestMethod.POST)
    public ModelAndView createTask(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("task")
                            Task task, BindingResult result){	    
	    String resultMessage = "Task creation failed.";
	    
	    try{
		    BrokerCaller taskService = ServiceFactory.getTaskService();
		    String taskId = taskService.addTask(listId, task.getTitle(), task.getNotes(), task.getDueDate());
		    Random randomGenerator = new Random();
		    int randomInt = randomGenerator.nextInt(1000);
		    Cookie newCookie = new Cookie("task" + String.valueOf(randomInt), taskId);
		    response.addCookie(newCookie);
		    resultMessage = "Task created successfully!";
		    this.sendNotification(task, Helper.getUserName(request));
	    }
	    catch(Throwable t){
	    	
	    }
		
         
        return new ModelAndView("taskCreationResult", "message", resultMessage);
	}

	/**
	 * Answers sending a notification that a task has been created.
	 * @param task
	 */
	private void sendNotification(Task task, String userName) {
		try{
			NotificationCaller notificationService = ServiceFactory.getNotificationService();
			String message = "Task has been created! - "+ task.getTitle();
			
			List<String> emailAddresses = Arrays.asList(task.getNotificationEmailRecipients().split(","));
			Iterator<String> iter = emailAddresses.iterator();
			while(iter.hasNext()){
				String next = iter.next();
				
				try{
					notificationService.sendEmail(next, message, "Task has been created!");
				}
				catch(Throwable t){
					
				}
			}
			
			List<String> textMessageNumbers = Arrays.asList(task.getNotificationTextRecipients().split(","));
			ListIterator<String> iter2 = textMessageNumbers.listIterator();
			String[] phoneCarriers = task.getNotificationTextRecipientsCarrier().split(",");
			while(iter2.hasNext()){
				String next = iter2.next();
				int thisIndex = iter2.nextIndex() - 1;
				try{
					notificationService.sendTxt(next, phoneCarriers[thisIndex], message);
				}
				catch(Throwable t){
					
				}
			}
			
			try{
				notificationService.sendTweet("jayset1", message);
			}
			catch(Throwable t){
				
			}
			
			//String Appname, String Name, String Email, String Txt, String Social
		}
		catch(Throwable t){
			
		}
	}

}
